<?php

// 公共助手函数

use app\admin\model\wanlshop\arrivalmenu\Userarrival;
use app\index\model\wanlshop\Pay;
use app\index\model\wanlshop\ShopMarginOrder;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\HttpResponseException;
use think\Request;
use think\Response;
use function EasyWeChat\Kernel\Support\get_client_ip;

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param string | array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @param int    $precision 小数位数
     * @return string
     */
    function format_bytes($size, $delimiter = '', $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 5; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        if (is_bool($domain) || stripos($cdnurl, '/') === 0) {
            $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        }
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = $v['field'] ?? $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = $v['display'] ?? str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = $v['primary'] ?? '';
            $v['column'] = $v['column'] ?? 'name';
            $v['model'] = $v['model'] ?? '';
            $v['table'] = $v['table'] ?? '';
            $v['name'] = $v['name'] ?? str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                // 优先判断使用table的配置
                $model = $v['table'] ? \think\Db::table($v['table']) : \think\Db::name($v['name']);
            }
            $primary = $v['primary'] ?: $model->getPk();
            $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $linedata = array_intersect_key($result[$n], $curr);
                    $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 使用短标签打印或返回数组结构
     * @param mixed   $data
     * @param boolean $return 是否返回数据
     * @return string
     */
    function var_export_short($data, $return = true)
    {
        return var_export($data, $return);
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] && config('fastadmin.cors_request_domain')) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                $response = Response::create('跨域检测无效', 'html', 403);
                throw new HttpResponseException($response);
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                $response = Response::create('', 'html');
                throw new HttpResponseException($response);
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}

if (!function_exists('url_clean')) {
    /**
     * 清理URL
     */
    function url_clean($url)
    {
        if (!check_url_allowed($url)) {
            return '';
        }
        return xss_clean($url);
    }
}

if (!function_exists('check_ip_allowed')) {
    /**
     * 检测IP是否允许
     * @param string $ip IP地址
     */
    function check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;
        $forbiddenipArr = config('site.forbiddenip');
        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
        if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
            $response = Response::create('请求无权访问', 'html', 403);
            throw new HttpResponseException($response);
        }
    }
}

if (!function_exists('check_url_allowed')) {
    /**
     * 检测URL是否允许
     * @param string $url URL
     * @return bool
     */
    function check_url_allowed($url = '')
    {
        //允许的主机列表
        $allowedHostArr = [
            strtolower(request()->host())
        ];

        if (empty($url)) {
            return true;
        }

        //如果是站内相对链接则允许
        if (preg_match("/^[\/a-z][a-z0-9][a-z0-9\.\/]+((\?|#).*)?\$/i", $url) && substr($url, 0, 2) !== '//') {
            return true;
        }

        //如果是站外链接则需要判断HOST是否允许
        if (preg_match("/((http[s]?:\/\/)+((?>[a-z\-0-9]{2,}\.)+[a-z]{2,8}|((?>([0-9]{1,3}\.)){3}[0-9]{1,3}))(:[0-9]{1,5})?)(?:\s|\/)/i", $url)) {
            $chkHost = parse_url(strtolower($url), PHP_URL_HOST);
            if ($chkHost && in_array($chkHost, $allowedHostArr)) {
                return true;
            }
        }

        return false;
    }
}

if (!function_exists('build_suffix_image')) {
    /**
     * 生成文件后缀图片
     * @param string $suffix 后缀
     * @param null   $background
     * @return string
     */
    function build_suffix_image($suffix, $background = null)
    {
        $suffix = mb_substr(strtoupper($suffix), 0, 4);
        $total = unpack('L', hash('adler32', $suffix, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $background = $background ? $background : "rgb({$r},{$g},{$b})";

        $icon = <<<EOT
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
            <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
            <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
            <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
            <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
            <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
            <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
        </svg>
EOT;
        return $icon;
    }
}

/**
 * 获取保证金
 ** @param $shopId
 * @param $keyvalue
 * @return int|mixed
 ** @throws \think\Exception
 */
function getMargin($shopId,$keyvalue){
    $shopInfo = \app\api\model\wanlshop\Shop::where(['id'=>$shopId,'is_bzj'=>0])->find();
    $margin = 0;
    if(!$shopInfo){
        return $margin;
    }
    $orderModel = new ShopMarginOrder();
    //已缴保证金
    $orderActualPayment = $orderModel->where(['shop_id'=>$shopId,'status'=>1])->sum('actual_payment');
    //总营业额
    $marginAll = (new Pay())->where(['pay_state'=>1,'shop_id'=>$shopId])->sum('order_price');
    $keyvalue = json_decode($keyvalue,true);

    if($keyvalue){
        if($orderActualPayment <= 0){
            $margin = $keyvalue[0];
        }else{
            unset($keyvalue[0]);

            foreach ($keyvalue as $k=>$v){
                if($marginAll > $k && $orderActualPayment <= $v){
                    $margin = $v;
                    break;
                }
            }
        }
    }
    return $margin;
}

/**
 * 限购逻辑
 ** @param $goodsId
 * @return bool
 ** @throws \think\Exception
 */
function isPurchaseLimit($goodsId,$userId){
    //检查当然用户是否购买过
    $orderIds = model('app\api\model\wanlshop\Order')->where(['user_id'=>$userId])->whereIn('state',
        '2,3,4,6')->column('id');
    if($orderIds){
        //查询是否购买过该商品
        $isBuy =  model('app\api\model\wanlshop\OrderGoods')->where('goods_id','=',$goodsId)->whereIn('order_id', $orderIds)->count();
        if($isBuy){
            return false;
        }
    }
    return true;
}

/**
 *判断ip是否来自国内
 * @return bool
 ** @throws Exception
 */
function isIpCn($ip): bool
{
//    $ip2region = new Ip2Region();
    $request =  Request::instance();
//    dump($request->langset());
//    $info = $ip2region->memorySearch($ip);
    $country = $info['region'] ?? '';
//    if (strpos($country, '中国') !== false) {
//        return true;
//    } else {
//        return false;
//    }
    if ($request->langset() !== 'en') {
        return true;
    } else {
        return false;
    }
}
/**
 * 确认收货，推荐商家或者厂家奖励
 * @param $pay
 * @param $order
 * @param $user
 * @throws DataNotFoundException
 * @throws DbException
 * @throws ModelNotFoundException
 */
function tuijianNew($pay,$order,$user){
    if($pay['is_commission'] == 0){
        //计算服务费, 平台转款给商家
        $fwf = $order['shop']['fwf'] / 100;
        $isIpCn = isIpCn(get_client_ip());
        $total_amount = $pay['price'];
        if($fwf > 0){
            //所扣的服务费
            $adminFwf = $allFwf = $pay['price']*$fwf;
            $shopMoney = $pay['price'] - $adminFwf;
            $bankFwf = 0;//银行手续费
            $tuijianShopPrice = 0;//推荐商家佣金
            $russianRecommendationPrice = 0;//推荐会员佣金
            if(!$isIpCn){
                //银行服务费
                $russianBankRatio = config('site.russian_bank_ratio') / 100;
                if($russianBankRatio > 0){
                    $bankFwf = $pay['price']*$russianBankRatio;
                    $adminFwf -= $bankFwf;
                }
            }
            //商家所得
            $pay['price'] = round($pay['price'] - $adminFwf,2);
            $shopUserInfo = \app\common\model\User::where(['id'=>$order['shop']['user_id']])->find();
            $parentUserId = 0;
            if(!empty($shopUserInfo['parent_user_id'])){
                $parentUserId = $shopUserInfo['parent_user_id'];
            }
            //判断商户是否存在上级
            if($parentUserId){
                //当然商户是厂家还是商家
                if($order['shop']['arrival_id'] == 1){
                    //厂家
                    $changjiaSales =  config('site.changjia_sales') / 100;
                    if($changjiaSales > 0){
                        $changjiaPrice = round($adminFwf * $changjiaSales,2);
                        if($changjiaPrice > 0){
                            controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$changjiaPrice, $parentUserId, '推荐厂家奖励', 'tuijian_changjia', $order['order_no']);
                        }
                    }
                }else if($order['shop']['arrival_id'] == 2){
                    //商家
                    if($isIpCn){
                        $tuijianShopSales =  config('site.shop_sales') / 100;
                    }else{
                        $tuijianShopSales =  config('site.russian_shop_sales') / 100;
                    }
                    if($tuijianShopSales > 0){
                        $tuijianShopPrice = round($adminFwf * $tuijianShopSales,2);
                        if($tuijianShopPrice > 0){
                            controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$tuijianShopPrice, $parentUserId, '推荐商家奖励', 'tuijianshop', $order['order_no']);
                        }
                    }
                }
            }
            //外国人每笔消费都会给上级收益
            if(!$isIpCn && $user['parent_user_id'] > 0){
                $russianRecommendation =  config('site.russian_recommendation') / 100;
                if($russianRecommendation > 0 && $adminFwf > 0){
                    $russianRecommendationPrice = round($adminFwf * $russianRecommendation,2);
                    if($russianRecommendationPrice > 0){
                        controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$russianRecommendationPrice, $user['parent_user_id'], 'Лавлах урамшуулал', 'tuijian', $order['order_no']);
                    }
                }
            }
            //服务费记录
            if($allFwf > 0){
                $serverLog  = new \app\admin\model\wanlshop\Serverlog();
                $serverLog->create(
                    [
                        'pay_id'=>$pay['id'],
                        'shop_id'=>$order['shop']['id'],
                        'user_id'  => $user['id'],
                        'total_amount'=>$total_amount,//订单金额
                         'handingfee'=>$allFwf,//总服务费
                        'taxes'=>$fwf,//服务费率
                        'qpay_fee'=>$bankFwf,//银行手续费
                        'promotion_shop'=>$tuijianShopPrice,//推荐商家
                        'promotion_user'=>$russianRecommendationPrice,//推荐会员
                        'platform_after'=> round($allFwf - $bankFwf - $tuijianShopPrice - $russianRecommendationPrice,2)  //推荐会员
                    ]);
            }
        }
        //好物推荐二级分销
        if(isset($order['recommendation_id']) && $order['recommendation_id']> 0){
            //查询分享人是否存在
            $recommendationInfo = \app\common\model\User::where(['id'=>$order['recommendation_id']])->find();
            if($recommendationInfo){
                //查询商品信息，获取分销数据
                if($order['one_commission'] > 0){
                    $pay['price'] = round($pay['price'] - $order['one_commission'],2);
                    controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$order['one_commission'], $order['recommendation_id'], '好物推荐直推收益', 'haowu_commission', $order['order_no']);
                }
                //如果购买者当前并没有好物推荐的上级，将此人绑定关系
                if(!$user['goods_parent_user_id']){
                    $user->goods_parent_user_id = $order->recommendation_id;
                    $user->save();
                }
                //间推
                if($recommendationInfo['goods_parent_user_id'] > 0){
                    $twoGoodsUserInfo = \app\common\model\User::where(['id'=>$recommendationInfo['goods_parent_user_id']])->find();
                    if($twoGoodsUserInfo && $order['two_commission']){
                        $pay['price'] = round($pay['price'] - $order['two_commission'],2);
                        controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$order['two_commission'], $twoGoodsUserInfo['id'], '好物推荐间推收益', 'haowu_commission', $order['order_no']);
                    }
                }
            }
        }
        controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$shopMoney, $order['shop']['user_id'], '买家确认收货', 'pay', $order['order_no']);
    }
}

/**
 * 线下收款分佣金
 * @param $order
 * @throws DataNotFoundException
 * @throws DbException
 * @throws ModelNotFoundException
 */
function commission($order){
    $allFwf = $adminFwf = $order['fwf'];//总服务费
    $user = \app\common\model\User::where(['id'=>$order['user_id']])->find();
    $russianBankRatio = config('site.russian_bank_ratio') / 100;
    $bankFwf = 0;
    $tuijianShopPrice = 0;
    $russianRecommendationPrice = 0;
    if($russianBankRatio > 0){
        $bankFwf = $order['actual_payment']*$russianBankRatio;//银行手续费
        $adminFwf -= $bankFwf;
    }
    $receiveInfo = \app\common\model\User::where(['id'=>$order['receive_id']])->find();
    $shopId = 0;
    //收款人是否是商户
    $shopInfo = \app\api\model\wanlshop\Shop::where(['user_id'=>$receiveInfo['id']])->find();
    //收款人上级是否存在
    if($shopInfo){
        $shopId = $shopInfo['id'];
        if(isset($receiveInfo['parent_user_id']) &&  $receiveInfo['parent_user_id'] > 0){
            if($shopInfo['arrival_id'] == 1){
                //厂家
                $changjiaSales =  config('site.changjia_sales') / 100;
                if($changjiaSales > 0){
                    $changjiaPrice = round($adminFwf * $changjiaSales,2);
                    if($changjiaPrice > 0){
                        controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$changjiaPrice, $receiveInfo['parent_user_id'], '推荐厂家奖励', 'tuijian_changjia', $order['order_no']);
                    }
                }
            }else if($shopInfo['arrival_id'] == 2){
                //商家
                $tuijianShopSales =  config('site.xianxi_shop_sales') / 100;
                $type = 'xianxia_tuijian_changjia';
                if($tuijianShopSales > 0){
                    $tuijianShopPrice = round($adminFwf * $tuijianShopSales,2);
                    if($tuijianShopPrice > 0){
                        controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$tuijianShopPrice, $receiveInfo['parent_user_id'], '推荐商家奖励', $type, $order['order_no']);
                    }
                }
            }
        }
        //外国人每笔消费都会给上级收益
        if(isset($user['parent_user_id']) && $user['parent_user_id'] > 0){
            $russianRecommendation =  config('site.xianxi_russian_recommendation') / 100;
            if($russianRecommendation > 0 && $adminFwf > 0){
                $russianRecommendationPrice = round($adminFwf * $russianRecommendation,2);
                if($russianRecommendationPrice > 0){
                    controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$russianRecommendationPrice, $user['parent_user_id'], 'Лавлах урамшуулал', 'tuijian', $order['order_no']);
                }
            }
        }
    }
    //服务费记录
    $serverLog  = new \app\admin\model\wanlshop\Serverlog();
    $serverLog->create(
        [
            'pay_id'        =>$order['id'],
            'shop_id'       => $shopId,
            'user_id'       => $order['user_id'],
            'type'          => 2,
            'total_amount'  => $order['actual_payment'],//订单金额
            'handingfee'    => $allFwf,//总服务费
            'taxes'         => config('site.shop_xianxia_fwf') / 100,//服务费率
            'qpay_fee'      => $bankFwf,//银行手续费
            'promotion_shop'=> $tuijianShopPrice,//推荐商家
            'promotion_user'=> $russianRecommendationPrice,//推荐会员
            'platform_after'=> round($allFwf - $bankFwf - $tuijianShopPrice - $russianRecommendationPrice,2)  //推荐会员
        ]);
}

/**
 * 厂家商家
 ** @param $userId
 * @return array
 ** @throws \think\Exception
 */
function cjsj($userId): array
{
    $isCj   = Userarrival::where(['user_id'=>$userId,'arrival_id'=>1])->count();
    $isShop = Userarrival::where(['user_id'=>$userId,'arrival_id'=>2])->count();
   return ['is_shop'=>$isShop,'is_cj'=>$isCj];
}


function httpGetRequest(string $url, array $params = [], array $headers = [], int $timeout = 15): array {
    // 1. 构建完整URL
    if (!empty($params)) {
        $queryString = http_build_query($params);
        $url .= (strpos($url, '?') === false ? '?' : '&') . $queryString;
    }

    // 2. 初始化cURL
    $ch = curl_init();
    if ($ch === false) {
        throw new Exception('cURL初始化失败');
    }

    // 3. 设置核心选项
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,    // 返回内容不直接输出
        CURLOPT_HEADER => false,           // 不包含响应头
        CURLOPT_TIMEOUT => $timeout,       // 总请求超时
        CURLOPT_CONNECTTIMEOUT => 5,        // 连接超时（秒）[3,7](@ref)
        CURLOPT_FOLLOWLOCATION => true,    // 跟随重定向[3,6](@ref)
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0, // 启用HTTP/2[3](@ref)
    ]);

    // 4. HTTPS安全设置（生产环境应验证证书！）
    if (strpos($url, 'https://') === 0) {
        curl_setopt_array($ch, [
            CURLOPT_SSL_VERIFYPEER => false, // 禁用证书验证（开发环境）
            CURLOPT_SSL_VERIFYHOST => 0      // 不检查主机名[2,8](@ref)
        ]);
    }

    // 5. 添加自定义请求头
    if (!empty($headers)) {
        $formattedHeaders = [];
        foreach ($headers as $key => $value) {
            $formattedHeaders[] = "$key: $value";
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $formattedHeaders);
    } else {
        // 默认User-Agent
        curl_setopt($ch, CURLOPT_USERAGENT,
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
        );
    }

    // 6. 执行请求并处理响应
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // 7. 错误处理
    if ($response === false || $httpCode >= 400) {
        $errorMsg = curl_error($ch) ?: "HTTP错误状态码: $httpCode";
        curl_close($ch);
        throw new Exception("cURL请求失败: $errorMsg | URL: $url");
    }

    // 8. 关闭资源
    curl_close($ch);

    return [
        'status' => $httpCode,
        'body' => $response
    ];
}

/**
 * 安全的图片下载函数
 * @param string $url      图片URL
 * @param string $savePath 保存路径
 * @throws Exception
 */
function downloadImage($url, $savePath) {
    // 初始化cURL
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,    // 跟随重定向
        CURLOPT_MAXREDIRS => 3,            // 最大重定向次数[3](@ref)
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => false,   // 生产环境应启用
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_BUFFERSIZE => 128 * 1024,  // 分块接收
        CURLOPT_NOPROGRESS => false
    ]);

    // 执行请求
    $imageData = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // 错误处理
    if (curl_errno($ch)) {
        throw new Exception("cURL错误: " . curl_error($ch));
    }
//    if ($httpCode !== 200) {
//        throw new Exception("HTTP状态码异常: $httpCode");
//    }


    // 保存文件
    if (!file_put_contents($savePath, $imageData)) {
        throw new Exception("文件写入失败，检查目录权限");
    }
    curl_close($ch);
}

/**
 * 计算签名
 *
 * @param string $appId    应用ID
 * @param string $q        查询字符串
 * @param string $salt     随机盐值
 * @param string $curtime  当前时间戳
 * @param string $appKey   应用密钥
 * @return string          返回SHA256签名（小写十六进制）
 */
function calculateSignature($appId, $q, $salt, $curtime, $appKey) {
    // 计算input值（根据q长度动态处理）
    // 拼接签名原始字符串
    $signString = $appId . getInput($q) . $salt . $curtime . $appKey;

    // 生成SHA256签名
    return hash('sha256', $signString);
}

function getInput($q)
{
    if (empty($q)) {
        return null;
    }
    $len = mb_strlen($q, 'utf-8');
    return $len <= 20 ? $q : (mb_substr($q, 0, 10) . $len . mb_substr($q, $len - 10, $len));
}

/**
 * 动态语言翻译
 ** @param string $to 翻译语种
 * @param string $type 翻译模块
 * @param string $key 翻译语言
 * @return array|mixed
 ** @throws \think\Exception
 */
function language($to, $type,$key){
    $redis = \addons\wanlshop\library\WanlSdk\Common::redis();
    $redisKey = $type.':'.$to.'-'.$key;
    $text = $redis->get($redisKey);
    if(!$text){
        $data = (new \app\common\library\Youdao)->send($key,$to);
        if(!empty($data['translation'][0])){
            $redis->set($redisKey, $data['translation'][0]);
            $text = $data['translation'][0];
        }
    }
    return $text;
}


function containsChinese($str) {
    return preg_match('/[\x{4e00}-\x{9fa5}]/u', $str);
}

/**
 * 根据URL判断国内商家还是国外商家
 * @return bool
 */

function isUrlRussian(): bool
{
    $url = 'happygomall';
    if(strpos($_SERVER['HTTP_HOST'], $url) !== false){
       return true;
    }else{
        return false;
    }
}

/**
 * 替换数组的键和值
 * @param array $array 原始数组
 * @param callable|null $keyCallback 键替换回调函数（可选）
 * @param callable|null $valueCallback 值替换回调函数（可选）
 * @return array 替换后的新数组
 */
function replaceArrayKeysAndValues(array $array, ?callable $keyCallback = null, ?callable $valueCallback = null): array {
    $result = [];
    foreach ($array as $key => $value) {
        // 应用键替换回调（若提供）
        $newKey = $keyCallback ? $keyCallback($key) : $key;
        // 应用值替换回调（若提供）
        $newValue = $valueCallback ? $valueCallback($value) : $value;
        // 确保新键为合法类型（字符串或整数）
        if (!is_string($newKey) && !is_int($newKey)) {
            throw new InvalidArgumentException("Array keys must be strings or integers");
        }
        $result[$newKey] = $newValue;
    }
    return $result;
}


/**
 * 生成二维码
 */
function shengcode($url,$mid,$path="membercode"){
    vendor('phpqrcode.phpqrcode');
    //dump($url);exit();
    $size=4;    //图片大小
    $errorCorrectionLevel = "Q"; // 容错级别：L、M、Q、H
    $matrixPointSize = "8"; // 点的大小：1到10
//实例化
    $qr = new \QRcode();
//生成二维码图片
    $filename = './'.$path.'/'.$mid.'.jpg';
    //检查图片是否存在，避免重复生成
//    if(file_exists($filename)){
//        return $filename;
//    }
    $qr::png($url, $filename, $errorCorrectionLevel, $matrixPointSize,2);
    $logo = 'logo.jpg';
    if ($filename !== FALSE) {
        $QR = imagecreatefromstring(file_get_contents($filename));
        $logo = imagecreatefromstring(file_get_contents($logo));
        $QR_width = imagesx($QR);//二维码图片宽度
        $QR_height = imagesy($QR);//二维码图片高度
        $logo_width = imagesx($logo);//logo图片宽度
        $logo_height = imagesy($logo);//logo图片高度
        $logo_qr_width = $QR_width / 5;
        $scale = $logo_width/$logo_qr_width;
        $logo_qr_height = $logo_height/$scale;
        $from_width = ($QR_width - $logo_qr_width) / 2;
        //重新组合图片并调整大小
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
            $logo_qr_height, $logo_width, $logo_height);
    }
    imagepng($QR, $filename);
    return $filename;
}





